/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.config.FileProperties;
import me.zhengjie.modules.system.domain.Supplier;
import me.zhengjie.modules.system.domain.SupplierAuditHistory;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.SupplierAuditHistoryService;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.SupplierRepository;
import me.zhengjie.modules.system.service.SupplierService;
import me.zhengjie.modules.system.service.dto.SupplierDto;
import me.zhengjie.modules.system.service.dto.SupplierQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.SupplierMapper;
import me.zhengjie.utils.enums.AuditEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * @author berry
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-06-06
 **/
@Service
@RequiredArgsConstructor
public class SupplierServiceImpl implements SupplierService {

    private final SupplierRepository supplierRepository;
    private final SupplierAuditHistoryService supplierAuditHistoryService;
    private final SupplierMapper supplierMapper;
    private final FileProperties properties;

    @Override
    public Map<String, Object> queryAll(SupplierQueryCriteria criteria, Pageable pageable) {
        Page<Supplier> page = supplierRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(supplierMapper::toDto));
    }

    @Override
    public List<SupplierDto> queryAll(SupplierQueryCriteria criteria) {
        return supplierMapper.toDto(supplierRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public SupplierDto findById(Long id) {
        Supplier supplier = supplierRepository.findById(id).orElseGet(Supplier::new);
        ValidationUtil.isNull(supplier.getId(), "Supplier", "supplierId", id);
        return supplierMapper.toDto(supplier);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SupplierDto create(Supplier resources) {
        resources.setStatus(AuditEnum.INIT);
        return supplierMapper.toDto(supplierRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Supplier resources) {
        Supplier supplier = supplierRepository.findById(resources.getId()).orElseGet(Supplier::new);
        ValidationUtil.isNull(supplier.getId(), "Supplier", "id", resources.getId());
        ValidationUtil.isNotBelong(supplier.getCreateBy(), SecurityUtils.getCurrentUsername());
        supplier.copy(resources);
        supplierRepository.save(supplier);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Supplier.RequestStatus requestStatus) {
        Supplier supplier = supplierRepository.findById(requestStatus.getId()).orElseGet(Supplier::new);
        ValidationUtil.isNull(supplier.getId(), "Supplier", "id", requestStatus.getId());
        ValidationUtil.notNeedUpdate(requestStatus.getStatus(), supplier.getStatus(), "status");
        int success = supplierRepository.updateStatus(requestStatus.getId(), requestStatus.getStatus().getCode());
        if (success == 1) {
            SupplierAuditHistory supplierAuditHistory = SupplierAuditHistory.fromSupplier(supplier);
            supplierAuditHistory.setStatus(requestStatus.getStatus());
            supplierAuditHistoryService.create(supplierAuditHistory);
        }
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            supplierRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SupplierDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SupplierDto supplier : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("供应商名称", supplier.getName());
            map.put("营业执照", supplier.getLicense());
            map.put("状态", supplier.getStatus());
            map.put("供应商性质", supplier.getProperties());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> uploadLicense(MultipartFile multipartFile) {
        File file = FileUtil.upload(multipartFile, properties.getPath().getLicense());
        return new HashMap<String, String>(1) {{
            put("license", file.getName());
        }};
    }


}